package com.example.oraceldemo.pojo;

import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtils {

    public static String doGet(String url, Map<String, String> param) {
        // Httpclient
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // http GET
            HttpGet httpGet = new HttpGet(uri);

            // ִ
            response = httpclient.execute(httpGet);
            //
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(),
                        "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {
        // Httpclient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // Http Post
            HttpPost httpPost = new HttpPost(url);

            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
                        paramList, "utf-8");
                httpPost.setEntity(entity);
            }
            //http
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, null);
    }

    /**
     * @param url
     * @param json
     * @return {username:"",pass:""}
     */
    public static String doPostJson(String url, String json, String token) {
        // Httpclient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).build();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // Http Post
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            if (token != null) {
                BasicHeader header = new BasicHeader("Authorization", token);
                httpPost.setHeader(header);
            }

            StringEntity entity = new StringEntity(json,
                    ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // ִhttp

            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    /**
     * timeStampData data[3] = signCert data[4] = fileTnsValue data[5] =
     * fileSignValue data[6] = fileUrl data[7] = fileSignCert data[8] =
     * fileHashCode
     **/
    public static String[] readJSON(String jsonstr) {
        try {

            JsonParser parser = new JsonParser();
            JsonObject object = (JsonObject) parser.parse(jsonstr);
            String status = object.get("status").getAsString();
            if ("success".equals(status)) {
                JsonObject dataobj = object.get("data").getAsJsonObject();
                String[] data = new String[9];
                data[0] = dataobj.get("signData").getAsString();
                data[1] = dataobj.get("treeHash").getAsString();
                data[2] = dataobj.get("timeStampData").getAsString();
                data[3] = dataobj.get("signCert").getAsString();
                data[4] = dataobj.get("fileTnsValue").getAsString();
                data[5] = dataobj.get("fileSignValue").getAsString();
                data[6] = dataobj.get("fileUrl").getAsString();
                data[7] = dataobj.get("fileSignCert").getAsString();
                data[8] = dataobj.get("fileHashCode").getAsString();
                return data;
            }
            return null;
        } catch (JsonIOException e) {
            e.printStackTrace();
            return null;
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * data[0] = signData
     * data[1] = treeHash
     * data[2] = timeStampData
     * data[3] = signCert
     **/
    public static String[] readJSONForWorkMod1(String jsonstr) {
        try {

            JsonParser parser = new JsonParser();
            JsonObject object = (JsonObject) parser.parse(jsonstr);
            String status = object.get("status").getAsString();
            if ("success".equals(status)) {
                JsonObject dataobj = object.get("data").getAsJsonObject();
                String[] data = new String[4];
                data[0] = dataobj.get("signData").getAsString();
                data[1] = dataobj.get("treeHash").getAsString();
                data[2] = dataobj.get("timeStampData").getAsString();
                data[3] = dataobj.get("signCert").getAsString();
                return data;
            }
            return null;
        } catch (JsonIOException e) {
            e.printStackTrace();
            return null;
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String[] readJSONForWorkModFei(String jsonstr) {
        try {

            JsonParser parser = new JsonParser();
            JsonObject object = (JsonObject) parser.parse(jsonstr);
            String status = object.get("status").getAsString();
            if ("success".equals(status)) {
                JsonObject dataobj = object.get("data").getAsJsonObject();
                String[] data = new String[4];
                data[0] = dataobj.get("signData").getAsString();
                data[1] = dataobj.get("treeHash").getAsString();
                data[2] = dataobj.get("timeStampData").getAsString();
                data[3] = dataobj.get("signPubKey").getAsString();
                return data;
            }
            return null;
        } catch (JsonIOException e) {
            e.printStackTrace();
            return null;
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            return null;
        }
    }
}
